/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.web.controller;

import cn.easyplatform.lang.Strings;
import cn.easyplatform.messages.request.SimpleRequestMessage;
import cn.easyplatform.messages.vos.admin.DeviceMapVo;
import cn.easyplatform.messages.vos.admin.TemplateVo;
import cn.easyplatform.spi.service.AdminService;
import cn.easyplatform.type.IResponseMessage;
import cn.easyplatform.web.dialog.MessageBox;
import cn.easyplatform.web.service.ServiceLocator;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.select.SelectorComposer;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zk.ui.util.Clients;
import org.zkoss.zkmax.zul.Scrollview;
import org.zkoss.zul.*;
import org.zkoss.zul.theme.Themes;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class UserSettingsController extends SelectorComposer<Window> {

    /**
     *
     */
    private static final long serialVersionUID = 1L;
    private Vlayout currentLayout;

    private List<String> ids;
    private List<String> names;

    @Wire("scrollview#themes")
    private Scrollview themes;

    public void doAfterCompose(Window win) throws Exception {
        super.doAfterCompose(win);
        List<String> list = new ArrayList<>();
        for (String themeName : Themes.getThemes()) {
            if (themeName.endsWith("_c") || themeName.equals("sapphire") || themeName.equals("breeze") || themeName.equals("silvertail"))
                list.add(themeName);
        }
        String[] id = new String[]{"Aquamarine", "atrovirens_c", "Aurora", "Blueberry", "Emerald", "Iceblue", "Lavender",
                "Marigold", "Montana", "Mysterious", "Office", "Olive", "Poppy", "Ruby", "Space"};
        String[] name = new String[]{Labels.getLabel("theme.name.color.aquamarine"), Labels.getLabel("theme.name.color.atrovirens_c"),
                Labels.getLabel("theme.name.color.aurora"), Labels.getLabel("theme.name.color.blueberry"), Labels.getLabel("theme.name.color.emerald"),
                Labels.getLabel("theme.name.color.iceblue"), Labels.getLabel("theme.name.color.lavender"),Labels.getLabel("theme.name.color.marigold"),
                Labels.getLabel("theme.name.color.montana"), Labels.getLabel("theme.name.color.mysterious"), Labels.getLabel("theme.name.color.office"),
                Labels.getLabel("theme.name.color.olive"), Labels.getLabel("theme.name.color.poppy"), Labels.getLabel("theme.name.color.ruby"),
                Labels.getLabel("theme.name.color.space")};
        ids = Arrays.asList(id);
        names = Arrays.asList(name);
        Collections.sort(list);
        if (list != null || list.size() > 0) {
            //每一行最外层控件
            Div contentDiv = new Div();
            contentDiv.setHflex("1");
            contentDiv.setStyle("display: flex;flex-direction: row;flex-wrap: wrap;min-width:164px;justify-content: flex-start;");
            themes.appendChild(contentDiv);
            for (int index = 0; index < list.size(); index++) {
                String displayName = Themes.getDisplayName(list.get(index));
                Integer showIndex = ids.indexOf(displayName.split(" ")[0]);
                if (showIndex >= 0) {
                    new ThemesCell(list.get(index), displayName.split(" ")[0], contentDiv);
                }
            }
        }
        /*
        String theme = Themes.getCurrentTheme();
        Radio selectedItem = null;
        int i = 0;
        Row row = null;
        for (String themeName : list) {
            String displayName = Themes.getDisplayName(themeName);
            Radio radio = new Radio(displayName.split(" ")[0], "/images/theme/Amber.jpg");
            radio.setValue(themeName);
            if (themeName.equals(theme))
                selectedItem = radio;
            if (i % 2 == 0) {
                Component rows = themes.getFirstChild().getFirstChild();
                row = new Row();
                rows.appendChild(row);
            }
            row.appendChild(radio);
            i++;
        }
        if (selectedItem != null)
            themes.setSelectedItem(selectedItem);*/
        win.doHighlighted();
    }

    @Listen("onClick=#submit")
    public void submit() {
        if (currentLayout != null) {
            String theme = currentLayout.getId();
		    if (!theme.equals(Themes.getCurrentTheme())) {
			    Themes.setTheme(Executions.getCurrent(), theme);
                AdminService as = ServiceLocator.lookup(AdminService.class);
                IResponseMessage<?> resp = as.getConfig(new SimpleRequestMessage("template"));
                if (resp.isSuccess()) {
                    TemplateVo templateVo = (TemplateVo) resp.getBody();
                    for (DeviceMapVo dm : templateVo.getDevices()) {
                        if ("ajax".equals(dm.getType())) {
                            dm.setTheme(theme);
                        }
                    }
                    resp = as.saveProject(new SimpleRequestMessage(templateVo));
                    if (!resp.isSuccess())
                        MessageBox.showMessage(resp);
                }
			    Clients.confirmClose(null);
			    Executions.getCurrent().sendRedirect("");
		    }
		    themes.getRoot().detach();
        }
    }

    private class ThemesCell implements EventListener<Event> {

        public ThemesCell(String themeId,String themeName, Component parentLayout) {
            if (Strings.isBlank(themeName)) {
                Div div = new Div();
                div.setHflex("1");
                parentLayout.appendChild(div);
            } else  {
                Integer index = ids.indexOf(themeName);
                Vlayout contentLayout = new Vlayout();
                contentLayout.setSpacing("0");
                contentLayout.setHeight("200px");
                contentLayout.setWidth("164px");
                contentLayout.setStyle("text-align: center;");//;border:#195B40 solid 2px;
                contentLayout.setSclass("ui-div-normal");
                contentLayout.addEventListener(Events.ON_CLICK, this);
                contentLayout.setId(themeId);
                parentLayout.appendChild(contentLayout);

                Div oneDiv = new Div();
                oneDiv.setHeight("15px");
                contentLayout.appendChild(oneDiv);

                Image contentImage = new Image();
                contentImage.setSrc("~./img/theme/" + themeName +".png");
                contentImage.setHeight("137px");
                contentImage.setWidth("137px");
                contentLayout.appendChild(contentImage);

                Div secondDiv = new Div();
                secondDiv.setHeight("8px");
                contentLayout.appendChild(secondDiv);

                Label contentLabel = new Label();
                contentLabel.setValue(names.get(index));
                contentLabel.setStyle("font-size:12px;border-radius: 14px;padding: 2px 8px;");
                contentLayout.appendChild(contentLabel);

                Div lastDiv = new Div();
                lastDiv.setHeight("8px");
                contentLayout.appendChild(lastDiv);
                String theme = Themes.getCurrentTheme();
                if (theme.equals(themeId)) {
                    currentLayout = contentLayout;
                    currentLayout.setSclass("ui-div-selected");
                }
            }
        }
        @Override
        public void onEvent(Event event) throws Exception {
            if (event.getTarget() instanceof Vlayout) {
                if (currentLayout != event.getTarget()) {
                    ((Vlayout) event.getTarget()).setSclass("ui-div-selected");
                    currentLayout.setSclass("ui-div-normal");
                    currentLayout = (Vlayout) event.getTarget();
                }
            }
        }
    }
}
